<?php

require_once "./class/WeChat/XMLUtility.php";

class WeChatMessage
{
    const MSGTYPE_TEXT = 'text'; 
    const MSGTYPE_NEWS = 'news';

    public $user = "";
    
    public $userInfo = "";

    public $developer = "";

    public $message  = array();

    public function retrieveMsg() {
        $postStr = file_get_contents("php://input");
        msg("Normal message. Content: " . $postStr);
        if (!empty($postStr)) {
            $this->message = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);          
            $this->user = $this->message['FromUserName'];
            $this->developer = $this->message['ToUserName'];
            return $this->message;
        } 
        return NULL;

    }

    public function replyText($text='') {
        $msg = array (
            'ToUserName' => $this->user,
            'FromUserName'=>$this->developer,
            'MsgType'=>self::MSGTYPE_TEXT,
            'Content'=>$text,
            'CreateTime'=>time()
        );

        $this->reply($msg);
    }

    public function replyNews($newsData=array()) {
        $count = count($newsData);

        $msg = array(
            'ToUserName' => $this->user,
            'FromUserName'=>$this->developer,
            'MsgType'=>self::MSGTYPE_NEWS,
            'CreateTime'=>time(),
            'ArticleCount'=>$count,
            'Articles'=>$newsData
        );

        $this->reply($msg);
    }

    private function reply($msg)
    {
        $xmldata=  XMLUtility::xml_encode($msg);
        msg("Generated xml body: " . $xmldata);
        echo $xmldata;
        exit;
    }
}

?>
